<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>ROBOT tray式放板机</title>

  <!-- Theme style -->
  <link rel="stylesheet" href="css/adminlte.min.css">
  <link href="css/style.css" rel="stylesheet" type="text/css">
  <script src="plugins/echarts.js"></script>


  <style>
    .check-item{
      margin: 0 5px;
    }

    input[type="checkbox"]:checked {
      background-color: #4CAF50; /* 选中状态下的背景颜色 */
    }

    html, body {
      height: 100%;
      margin: 0;
      background-color: #343a40;
      padding-top: 5px;
      overflow: hidden;
    }

  </style>
</head>
<body class="hold-transition sidebar-mini layout-fixed dark-mode">
<div class="wrapper" id="wrapper">
  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper" style="margin-left: 0;">
    <!-- Main content -->
    <section class="content">
      <div class="container-fluid">
        <div class="row" id="content">
        </div>
      </div>
    </section>
  </div>
</div>

<!-- jQuery -->
<script src="plugins/jquery/jquery.min.js"></script>
<script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="js/adminlte.js"></script>

<script src="js/template-web.js"></script>

<script type="text/html" id="tmp">
  <div  class="col-lg-3 col-6" >
    <div style="height: 2%" class="header-top">
      <p id="clock"></p>
    </div>
    <div style="height: 45%;" class="card card-row card-secondary">
      <div class="card-header">
        <h3 class="card-title">生产信息</h3>
        <div class="card-tools">
          <button type="button" class="btn btn-tool" data-card-widget="collapse">
            <i class="fas fa-minus"></i>
          </button>
        </div>
      </div>
      <div class="card-body p-0" style="display: block;">
        <table class="aligned-table">
          <tr>
            <td class="left">机种名称</td>
            <td class="colon">:</td>
            <td class="right">{{project}}</td>
          </tr>
          <tr>
            <td class="left">批次号码</td>
            <td class="colon">:</td>
            <td class="right">{{lot_num}}</td>
          </tr>
          <tr>
            <td class="left">计划产量</td>
            <td class="colon">:</td>
            <td class="right">{{plan_count}}</td>
          </tr>
          <tr>
            <td class="left">实际产出</td>
            <td class="colon">:</td>
            <td class="right">{{actual_num}}</td>
          </tr>
          <tr>
            <td class="left">N G 数量</td>
            <td class="colon">:</td>
            <td class="right">{{NG_num}}</td>
          </tr>
          <tr>
            <td class="left">累计产出</td>
            <td class="colon">:</td>
            <td class="right">{{today_capacity}}</td>
          </tr>
          <tr>
            <td class="left">今日UPH</td>
            <td class="colon">:</td>
            <td class="right">{{uph}}</td>
          </tr>
          <tr>
            <td class="left">预计完成时间</td>
            <td class="colon">:</td>
            <td class="right">{{estimate_finish_time}}</td>
          </tr>
          <tr>
            <td class="left">&nbsp;</td>
            <td class="colon">&nbsp;</td>
            <td class="right">&nbsp;</td>
          </tr>
        </table>
      </div>
      <!-- /.card-body -->
    </div>
    <div style="height: 47%;" class="card card-dark">
      <div class="card-header">
        <h3 class="card-title">产能信息</h3>
        <div class="card-tools">
          <ul class="nav nav-pills ml-auto" style="line-height: 18px;" id="barChartNav">
            <li class="nav-item">
              <a class="nav-link" href="javascript:void(0);" data-key="ds_capacity"  onclick="onSwitchBarChart('ds_capacity')" data-toggle="tab">日</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="javascript:void(0);" data-key="ms_capacity"  onclick="onSwitchBarChart('ms_capacity')" data-toggle="tab">月</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="javascript:void(0);" data-key="ys_capacity"  onclick="onSwitchBarChart('ys_capacity')" data-toggle="tab">年</a>
            </li>
          </ul>
        </div>
      </div>
      <div class="card-body">
        <div class="chart tab-pane" style="height: 100%;width: 100%;">
<!--          <canvas id="barChart" width="100%" class="chartjs-render-monitor between-chart"></canvas>-->
          <div id="barChart" style="width: 100%;height: 100%"></div>
        </div>
      </div>
      <!-- /.card-body -->
    </div>
  </div>
  <div  class="col-lg-6 col-12">
    <div style="height: 2%" class="header-top">
      &nbsp;
    </div>
    <div style="margin-bottom: 0;" class="card card-row card-secondary">
      <div class="card-header">
        <h2 class="card-title">ROBOT tray式放板机</h2>
        <h2 class="card-title float-right">ELR-24D168</h2>
      </div>
      <div class="card-body">
        <div class="row">
          <div id="checkboxGroup" class="card-body" style="display: flex;justify-content: space-between;padding:0 10px">
            <div class="custom-control check-item">
              <label id="IDLE" data-name=" 待机 "></label>
            </div>
            <div class="custom-control custom-checkbox check-item">
              <label id="RUN" data-name=" 运行 "></label>
            </div>
            <div class="custom-control custom-checkbox check-item">
              <label id="STOP" data-name=" 停机 "></label>
            </div>
            <div class="custom-control  check-item">
              <label id="RUN1" data-name=" 维修 "></label>
            </div>
            <div class="custom-control custom-checkbox check-item">
              <label id="RUN2" data-name=" 保养 "></label>
            </div>
            <div class="custom-control custom-checkbox check-item">
              <label id="ALARM" data-name=" 故障 "></label>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div style="margin-bottom: 15px;" class="card card-dark">
      <div class="card-body" style="padding-top: 0">
        <div class="row">
          <div class="col-3 col-sm-3 content-item">
            <div class="badge bg-primary d-inline-flex content-item-button">
              <span>{{today_capacity}}</span>
              <span>今日产量</span>
            </div>
            <div class="badge bg-primary d-inline-flex content-item-button">
              <span>{{today_alarm_time}}</span>
              <span>今日异常</span>
            </div>
            <div class="badge bg-primary d-inline-flex content-item-button">
              <span>{{today_finish_rate}}</span>
              <span>今日完成率</span>
            </div>
          </div>
          <div class="col-6 col-sm-6 content-item-middle">
            <img id="imgX" style="padding: 5px" class="img-fluid"  alt="Photo">
          </div>
          <div class="col-3 col-sm-3 content-item" style="align-items: flex-end">
            <div class="badge bg-primary d-inline-flex content-item-button float-right">
              <span>{{run_duration}}</span>
              <span>运行时长</span>
            </div>
            <div class="badge bg-primary d-inline-flex content-item-button float-right">
              <span>{{alram_duration}}</span>
              <span>异常时长</span>
            </div>
            <div class="badge bg-primary d-inline-flex content-item-button float-right">
              <span>{{d_utilization_rate_pen}}</span>
              <span>今日稼动率</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div style="margin-bottom: 0;" class="card card-dark">
      <div class="card-body" style="padding: 0 1.25rem">
      <div class="row" style="margin-top: 0.5rem">
          <div class="col-12 col-sm-12">
            <!-- flat style with animated hover effect -->
            <div class="breadcrumb flat dark-mode" id="breadcrumb">
              <a id="nav1" class="" href="javascript:void(0);" onclick="onSwitchNav('./static/images/ROBOT tray式放板机/1.tray取板.png',this)">Tray盘取板</a >
              <a id="nav2" class="" href="javascript:void(0);" onclick="onSwitchNav('./static/images/ROBOT tray式放板机/2.扫码判定.png',this)">扫码判定</a >
              <a id="nav3" class="" href="javascript:void(0);" onclick="onSwitchNav('./static/images/ROBOT tray式放板机/3.视觉定位.png',this)">视觉定位</a >
              <a id="nav4" class="" href="javascript:void(0);" onclick="onSwitchNav('./static/images/ROBOT tray式放板机/4.机台上板.png',this)">机台上板</a >
              <a id="nav5" class="" href="javascript:void(0);" onclick="onSwitchNav('./static/images/ROBOT tray式放板机/5.异常处理.png',this)">异常处理</a >            </div>
          </div>
        </div>
      </div>
    </div>
    <div style="" class="card card-dark">
      <div class="card-body" style="padding: 0 1.25rem">
        <div class="row" style="height: 70%" >
          <div class="col-lg-4 col-6" style="padding: 2px" >
            <!-- LINE CHART -->
            <div class="card card-info">
              <div class="card-header" style="background-color: #14314c">
                <h3 class="card-title">耗电量统计</h3>
              </div>
              <div class="card-body">
                <div class="chart" style="height: 100%">
<!--                  <canvas id="lineChart1" class="chartjs-render-monitor chart-style"></canvas>-->
                  <div id="lineChart1" style="width: 100%;height:100%"></div>

                </div>
              </div>
              <!-- /.card-body -->
            </div>
            <!-- /.card -->
          </div>
          <div class="col-lg-4 col-6" style="padding: 2px">
            <!-- LINE CHART -->
            <div class="card card-info">
              <div class="card-header" style="background-color: #14314c">
                <h3 class="card-title">气缸耗气量统计</h3>
              </div>
              <div class="card-body">
                <div class="chart">
<!--                  <canvas id="lineChart2" class="chart-style"></canvas>-->
                  <div id="lineChart2" style="width: 100%;height:100%"></div>
                </div>
              </div>
              <!-- /.card-body -->
            </div>
            <!-- /.card -->
          </div>
          <div class="col-lg-4 col-6" style="padding: 2px">
            <!-- LINE CHART -->
            <div class="card card-info" >
              <div class="card-header" style="background-color: #14314c">
                <h3 class="card-title">真空耗气量统计</h3>
              </div>
              <div class="card-body">
                <div class="chart">
                  <div id="lineChart3" style="width: 100%;height:100%"></div>
                </div>
              </div>
              <!-- /.card-body -->
            </div>
            <!-- /.card -->
          </div>
        </div>
      </div>
    </div>
  </div>
  <div  class="col-lg-3 col-6">
    <div style="height: 2%" class="header-top">
      <p>操作人员：{{operator}}</p>
    </div>
    <div style="height: 45% " class="card card-row card-secondary">
      <div class="card-header">
        <h3 class="card-title">设备管理</h3>

        <div class="card-tools">
          <button type="button" class="btn btn-tool" data-card-widget="collapse">
            <i class="fas fa-minus"></i>
          </button>
        </div>
      </div>
      <div class="card-body p-0" style="display: block;">
        <table class="aligned-table">
          <tr>
            <td class="left">开机时间</td>
            <td class="colon">:</td>
            <td class="right">{{boot_time}}</td>
          </tr>
          <tr>
            <td class="left">运行时长</td>
            <td class="colon">:</td>
            <td class="right">{{run_duration}}</td>
          </tr>
          <tr>
            <td class="left">异常时长</td>
            <td class="colon">:</td>
            <td class="right">{{alram_duration}}</td>
          </tr>
          <tr>
            <td class="left">累计时长</td>
            <td class="colon">:</td>
            <td class="right">{{total_duration}}</td>
          </tr>
          <tr>
            <td class="left">今日稼动率</td>
            <td class="colon">:</td>
            <td class="right">{{d_utilization_rate_pen}}</td>
          </tr>
          <tr>
            <td class="left">累计稼动率</td>
            <td class="colon">:</td>
            <td class="right">{{t_utilization_rate_pen}}</td>
          </tr>
          <tr>
            <td class="left">EAP状态</td>
            <td class="colon">:</td>
            <td class="right">{{EAP_status}}</td>
          </tr>
          <tr>
            <td class="left">控制模式</td>
            <td class="colon">:</td>
            <td class="right">{{task_mode}}</td>
          </tr>
          <tr>
            <td class="left">&nbsp;</td>
            <td class="colon">&nbsp;</td>
            <td class="right">&nbsp;</td>
          </tr>
        </table>
      </div>
      <!-- /.card-body -->
    </div>
    <div style="height: 47%;" class="card card-dark">
      <div class="card-header">
        <h3 class="card-title">稼动率</h3>
        <div class="card-tools">
          <ul class="nav nav-pills ml-auto" id="pieChartNav" style="line-height: 18px;">
            <li class="nav-item">
              <a class="nav-link" href="javascript:void(0);"  onclick="onSwitchPieChart('d_utilization_rate')" data-key="d_utilization_rate" data-toggle="tab">日</a>
            </li>
<!--            <li class="nav-item">-->
<!--              <a class="nav-link" href="javascript:void(0);"   onclick="onSwitchPieChart('ws_utilization')" data-toggle="tab">周</a>-->
<!--            </li>-->
            <li class="nav-item">
              <a class="nav-link" href="javascript:void(0);"   onclick="onSwitchPieChart('m_utilization_rate')" data-key="m_utilization_rate" data-toggle="tab">月</a>
            </li>
          </ul>
        </div>
      </div>
      <div class="card-body">
        <div class="chart tab-pane" style="height: 100%" >
<!--          <div id="donut-chart" class="between-chart" style="height: 250px"></div>-->
<!--          <canvas id="pieChart" width="100%" class="chartjs-render-monitor between-chart"></canvas>-->
          <div id="pieChart" style="width: 100%;height:100%"></div>
        </div>
      </div>
      <!-- /.card-body -->



    </div>
  </div>
</script>
<script src="mock/mockdata.js"></script>
<script type="text/javascript">

</script>

<script>

  const req_address = "mock/api_data3.json"

  var barKey = 'ds_capacity'
  var pieKey = 'd_utilization_rate'
  var nav = 'nav1'

  var jsonData  = {};
  var fixedData  = {};
 
  $(function () {
    // mockGetData();
    // setInterval(mockGetData, 5000);
    // setInterval(displayTime, 1000);
    
    getData();
    // setInterval(getData, 5000);
    setInterval(displayTime, 1000);
  });


 function getData() {
    $.getJSON(req_address, function(res) {
      fixedData = fixData(res);
      refresh();
    });
  }
  function mockGetData() {
    mockTime = (mockTime+1)%2;
    jsonData = mockData()[mockTime];
    fixedData = fixData(jsonData);
    refresh();
  }

  function refresh() {
    var html = template('tmp',fixedData) //通过模板的id,将数据和和模板绑定,并用一个变量接收
    $('#content').html(html) //将变量插入页面结构中渲染出来
    initState(fixedData);
    initChart(fixedData);
    initNav();
    displayTime();
  }

  function initNav() {
     $('#'+nav).addClass('active');
     $('#'+nav).click();
  }

  function initChart(data) {
    $('#barChartNav a[data-key='+barKey+']').addClass('active');
    barChartInit('barChart',data.Capacity_information,barKey)

    lineChartInit("lineChart1",data.power_consumption,title1(data.pc_total))
    lineChartInit("lineChart2",data.cylinder_consumption,title2(data.cc_total))
    lineChartInit("lineChart3",data.vacuum_comsumption,title3(data.vc_total))

    $('#pieChartNav a[data-key='+pieKey+']').addClass('active');
    pieChartInit('pieChart',data, pieKey)
  }

  function initState(data){
    if (data.device_state) {
      // 遍历选中的label元素
      $('#checkboxGroup label').each(function() {
        // 获取当前label的data-name属性值，并添加到数组中
        var dataName = $(this).data('name');
        var text = '&#x25A1;' + dataName;
        $(this).html(text);
      });

      let element = $('#'+ data.device_state);
      let color = data.device_state === 'RUN' ? 'cornflowerblue' : 'red';
      element.css({color: color});
      element.html('&#x25A0;' + element.data('name'));
    }
  }

  function onSwitchBarChart(key) {
    barChartInit('barChart',fixedData.Capacity_information,key);
    barKey = key;
  }

  function onSwitchPieChart(key) {
    pieChartInit('pieChart',fixedData, key);
    pieKey = key;
  }

  function onSwitchNav(url, element) {
    $('#imgX').attr('src', url);
    // 移除所有兄弟元素的 'active' 类
    Array.from(element.parentNode.children).forEach(function(sibling) {
      if (sibling !== element) {
        sibling.classList.remove('active');
      }
    }, this);
    // 为当前点击的元素添加 'active' 类
    element.classList.add('active');
    nav = element.id;
  }
 
  function barChartInit(id, data, key) {
    let map = data[key]
    let keys = []
    let values = []

    if (key === 'ds_capacity') {
      keys = Array.from({ length: 25 }, (_, index) => index.toString().padStart(2, '0'));
    }
    if (key === 'ms_capacity') {
      keys = Array.from({ length: 32 }, (_, index) => index.toString().padStart(2, '0'));
    }
    if (key === 'ys_capacity') {
      keys = Array.from({ length: 13 }, (_, index) => index.toString().padStart(2, '0'));
    }

    let _values = []
    keys.forEach(function(value, key) {
      if (value in map){
        _values.push(map[value])
      }else{
        _values.push(0)
      }
    })
    values = _values

    var myChart = echarts.init(document.getElementById(id),null,{
      height: 350
    });
    window.addEventListener('resize', function() {
      myChart.resize();
    });

    option = {
      animation: false, // 关闭动画
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: keys,
          axisTick: {
            alignWithLabel: true
          }
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: 'Direct',
          type: 'bar',
          barWidth: 'auto',
          data: values
        }
      ]
    };

    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);

  }

  /**
   * 数据修复
   * @param data
   * @returns {*}
   */
  function fixData(data) {
    var currentTime = $.now();
    var targetTime = new Date(data.boot_time).getTime();
    // 计算时间差（单位：秒）
    var timeDiff = Math.floor((currentTime - targetTime) / 1000);
    data.total_duration = targetTime ?  timeDiff : 'NaN';
    let uph = data.today_capacity / timeDiff * 60 * 60 ;
    data.uph = parseFloat(uph).toFixed(2);
    let today_finish_rate = data.actual_num / data.plan_count
    data.d_utilization_rate_pen =  parseFloat(data.d_utilization_rate * 100).toFixed(2) + '%'
    data.t_utilization_rate_pen = parseFloat(data.t_utilization_rate * 100).toFixed(2) + '%'
    data.today_finish_rate = parseFloat(today_finish_rate * 100).toFixed(2) + '%';
    nav = 'nav' + data.flow
    return data
  }


  function getMinutesSinceStartOfDay() {
    // 获取当前时间
    const now = new Date();

    // 获取当天零点的时间
    const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());

    // 计算当前时间与当天零点的时间差（以毫秒为单位）
    const timeDifference = now - startOfDay;

    // 将时间差转换为分钟
    const minutesSinceStartOfDay = Math.floor(timeDifference / (1000 * 60));

    return minutesSinceStartOfDay;
  }

  function title1(data) {
    const min  = getMinutesSinceStartOfDay()
    const value = parseFloat(data * 60 / min).toFixed(2);
    return [`总电气量：${data} kW·h`, `实时流量：${value} kw`]
  }

  function title2(data) {
    const min  = getMinutesSinceStartOfDay()
    const value = parseFloat(data / min).toFixed(2);
    return [`总耗电量：${data} L`,`实时流量：${value} L/min`]
  }

  function title3(data) {
    const min  = getMinutesSinceStartOfDay()
    const value = parseFloat(data / min).toFixed(2);
    return [`总电气量：${data} L`,`实时流量：${value} L/min`]
  }

  function getKeys(data) {
    const map = Object.keys(data)
            .sort((a, b) => a.localeCompare(b))
            .map(key => [key, data[key]]);
    return [...map.keys()]
  }

  function getValues(keys, data) {
    return $.map(keys, function(key) {
      return data[key];
    });
  }

  function lineChartInit(id, data, title){

    const keys = getKeys(data)
    const values = getValues(keys, data)

    var myChart = echarts.init(document.getElementById(id),null,{
      height: 260
    });

    window.addEventListener('resize', function() {
      myChart.resize();
    });

    option = {
      animation: false, // 关闭动画
      title: {
        text: title[0],
        subtext: title[1],
        left: 'center',
        textStyle:{
          color: '#FFFFFF',
          fontSize: 14,
          fontWeight: 'normal'
        }
      },
      xAxis: {
        type: 'category',
        data: keys
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: values,
          type: 'line',
          smooth: true
        }
      ]
    };

    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);

  }

  function pieChartInit(id, data, key){
    const x = data[key]
    var myChart = echarts.init(document.getElementById(id));
    window.addEventListener('resize', function() {
      myChart.resize();
    });
    const y  = parseFloat(1-x).toFixed(2)
    const t = parseFloat(x *100).toFixed(2) + '%';

    option = {
      animation: false, // 关闭动画
      emphasis:{
        disabled: true, // 是否关闭高亮状态
      },
      tooltip: {
        show: false // 是否展示提示框浮层
      },
      // animationDuration: 2000, // 动画时长
      legend: {
        top: '5%',
        left: 'center'
      },
      series: [
        {
          name: '稼动率',
          type: 'pie',
          radius: ['50%', '90%'],
          avoidLabelOverlap: false,
          // 主要代码在这里
          label: {
            normal: {
              show: true,
              position: 'center', // 展示在中间位置
              formatter:() => {
                return t
              },
              fontSize: 25,
              color: '#5470c6',
            },
          },
          itemStyle: {
            borderRadius: 8,
          },
          emphasis: {
            label: {
              show: false,
              fontSize: 40,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: y , itemStyle:{normal:{color:"rgba(245,245,245)"}}},
            { value: x},
          ],
          animationDelay: function (idx) {
            return idx * 100;
          }
        }
      ]
    };

    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
  }

  function  displayTime() {
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth() + 1; // 月份是从0开始的
    const day = today.getDate();
    let h = today.getHours();
    let m = today.getMinutes();
    let s = today.getSeconds();
    let d = today.getDay();
    // 添加前导零
    h = checkTime(h);
    m = checkTime(m);
    s = checkTime(s);
    // 星期几的数组
    const week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    document.getElementById('clock').innerHTML = year + '-' + month + '-' + day + '&nbsp;&nbsp;&nbsp;'+ h + ':' + m + ':' + s + ' ' + '&nbsp;&nbsp;&nbsp;' + week[d];
  }

  function checkTime(i) {
    if (i < 10) {i = "0" + i};
    return i;
  }

</script>

</body>
</html>
